/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package newkfp;

import Beans.AddedItem;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import newkfp.util.JsfUtil;
import pojos.Treausry;

/**
 *
 * @author labib.farag
 */
@ManagedBean(name = "billExporterInformationController")
@SessionScoped
public class BillExporterInformation {

    @ManagedProperty(value = "#{itemController}")
    ItemController itemController;
    Loger loger;
    @EJB
    private newkfp.LogFacade logFacade;
    @EJB
    private newkfp.TreausryFacade treausryFacade;
    @EJB
    private newkfp.CountryFacade countryFacade;
    private List<String> countries;
    private List<String> factories;
    //represent from 1 to 4 (meat - none meat - cheken etc ..) 
    private int mainItem;
    private String CDate;
    // represent submenue of item selected  
    private String selectedsubItem = "";
    private String selectedCountry = "";
    private String factory = "";
    private double total_Number;
    private double total_price;
    private double totalRow;
    private double unite_price;
    private boolean libra;
    private double totalKg;
    private String exporterName = "", exporterID;
    private Exporter selectedExporter;
    private Date billDate=new Date();
    //// information about bill and balance for Exporter 
    private double paied;
    private double discount;
    private boolean noExistence;
    ///// bill information 
    private int billNumber=1;
    private int docNumber=1;
    private double billTotal;
    private double bill_reminder;
    private double balanceAfterBill;
    private String billItemStatus="Regular";
    private Date expDate = new Date();
    @EJB
    private newkfp.BillFacade ejbFacade;
    @EJB
    private newkfp.BillFacade billFacad;
    @EJB
    private newkfp.BillItemFacade billItemFacad;
    private ArrayList<Quantity_Number> orderList =
            new ArrayList<Quantity_Number>();
    private ArrayList<AddedItem> add_Item =
            new ArrayList<AddedItem>();
    @EJB
    private newkfp.ExporterFacade exporterFacad;
    private Bill bill;
    @EJB
    private newkfp.ItemFacade itemFacad;

    public BillExporterInformation() {
        loger = new Loger(getLogFacade());
    }

    private BillFacade getFacade() {
        return ejbFacade;
    }

    public String getBillItemStatus() {
        return billItemStatus;
    }

    public void setBillItemStatus(String billItemStatus) {
        this.billItemStatus = billItemStatus;
    }

    public SelectItem[] getItems() {

        List<Item> itemsDB = getFacade().getItems(mainItem);


        HashSet<String> hashSet = new HashSet<String>();
        int i = 1;

        for (Item x : itemsDB) {
            hashSet.add(x.getItemName());
        }
        System.out.println("hashset:" + hashSet.size());
        SelectItem[] items = new SelectItem[hashSet.size() + 1];
        items[0] = new SelectItem("Select Item", "Select Item");
        for (String x : hashSet) {
            System.out.println("Country     " + x);
            items[i++] = new SelectItem(x, x);
        }
        System.out.println("items" + items.length);
        return items;
    }

    public int getMainItem() {
        return mainItem;
    }

    public void setMainItem(int mainItem) {
        this.mainItem = mainItem;
    }

    public String getSelectedsubItem() {
        return selectedsubItem;

    }

    public void setSelectedsubItem(String selectedsubItem) {
        this.selectedsubItem = selectedsubItem;
    }

    public void listenItemchanged(ValueChangeEvent vc) {
        System.out.println(" value changed ");
        System.out.println(" subitem is " + selectedsubItem);
    }

    public String getSelectedCountry() {
        return selectedCountry;
    }

    public void setSelectedCountry(String selectedCountry) {
        this.selectedCountry = selectedCountry;
    }

    /// combobox to fill from DB subItem
    public SelectItem[] getCountries() {

        //System.out.println(" selected suItem is " + selectedsubItem);

        List<Item> itemsDB = getFacade().getCountries(selectedsubItem);
        HashSet<Integer> countrys = new HashSet<Integer>();

        int i = 1;
        for (Item x : itemsDB) {
            countrys.add(x.getCountryID().getIdcountry());

        }
        SelectItem[] items = new SelectItem[countrys.size() + 1];
        items[0] = new SelectItem(0, "Select Country");

        for (int x : countrys) {
            Country c = countryFacade.find(x);

            items[i++] = new SelectItem(c.getIdcountry(), c.getCountryName());

        }
        return items;
    }

    public void itemListener(AjaxBehaviorEvent event) {
    }

    /// combobox to fill from DB subItem
    public SelectItem[] getFacoris() {

        Factory f;
        SelectItem[] items;
        System.out.println(" selected country is " + selectedCountry);
        if ("".equals(selectedCountry) || selectedCountry == null) {
            items = new SelectItem[1];
            items[0] = new SelectItem(0, "Select Factory");
        } else {

            List<Item> itemsDB = getFacade().getFactories(selectedsubItem, selectedCountry);
            items = new SelectItem[itemsDB.size() + 1];
            int i = 1;
            items[0] = new SelectItem(0, "Select Factory");
            for (Item x : itemsDB) {
                System.out.println("x.getFactoryID(), x.getFactoryID().getFactoryName()" + x.getFactoryID() + "   " + x.getFactoryID().getFactoryName());
                items[i++] = new SelectItem(x.getFactoryID().getIdFactory(), x.getFactoryID().getFactoryName());
            }
        }
        return items;
    }

    public String getFactory() {
        return factory;
    }

    public void setFactory(String factory) {
        this.factory = factory;
    }

    public String meat() {
        mainItem = 1;
        selectedsubItem = "";
        selectedCountry = "";
        return "ExporterBill";
    }

    public String nonMeat() {
        selectedsubItem = "";
        selectedCountry = "";
        mainItem = 2;
        return "ExporterBill";
    }

    public String checken() {
        selectedsubItem = "";
        selectedCountry = "";
        mainItem = 3;
        return "ExporterBill";
    }

    public String vegtable() {
        selectedsubItem = "";
        selectedCountry = "";
        mainItem = 4;
        return "ExporterBill";
    }
    //======================================================================quantity and number of it 
    private int quantity;
    private int number_quantity;

    public int getNumber_quantity() {
        return number_quantity;
    }

    public void setNumber_quantity(int number_quantity) {
        this.number_quantity = number_quantity;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public ArrayList<Quantity_Number> getOrderList() {
        return orderList;
    }

    public double getTotal_Number() {
        return total_Number;
    }

    public void setTotal_Number(double total_Number) {
        this.total_Number = total_Number;
    }

    public double getTotal_price() {
        total_price = 0;
        for (Iterator<Quantity_Number> it = orderList.iterator(); it.hasNext();) {
            Quantity_Number qu = it.next();
            total_price += (unite_price * qu.getNumber() * qu.getQuantity());

        }
        System.out.println(" --------------" + unite_price + "  ----  " + totalKg);
        System.out.println("-------------------------in getting  ajax ---------------------" + total_price);
        total_price = unite_price * totalKg;

        return total_price;
    }

    public void setTotal_price(double total_price) {
        this.total_price = total_price;
    }

    public double getUnite_price() {
        return unite_price;
    }

    public void setUnite_price(double unite_price) {
        this.unite_price = unite_price;
    }

    public boolean isLibra() {
        return libra;
    }

    public void setLibra(boolean libra) {
        this.libra = libra;
    }

    /**
     * @return the totalRow
     */
    public double getTotalRow() {
        return quantity * number_quantity;
    }

    /**
     * @param totalRow the totalRow to set
     */
    public void setTotalRow(double totalRow) {
        this.totalRow = totalRow;
    }

    /**
     * @return the totalKg
     */
    public double getTotalKg() {
        return totalKg += getTotalRow();
    }

    /**
     * @param totalKg the totalKg to set
     */
    public void setTotalKg(double totalKg) {
        this.totalKg = totalKg;
    }

    public String calculate() {
        return "CalculationExporter";
    }

    public String finishCalculation() {
        return "ExporterBill";
    }

    public String getExporterName() {
        return exporterName;
    }

    public void setExporterName(String exporterName) {
        this.exporterName = exporterName;
    }

    public String getExporterID() {
        return exporterID;
    }

    public void setExporterID(String exporterID) {
        this.exporterID = exporterID;
    }

    public Exporter getSelectedExporter() {
        if (getExporterName() != null && !getExporterName().trim().isEmpty()) {
            Exporter r = getFacade().getExporterByName(getExporterName());



            return selectedExporter = r;
        } else {

//            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/Bundle").getString("UserNotFound"));
            return null;
        }

    }

    public void setSelectedExporter(Exporter selectedExporter) {
        this.selectedExporter = selectedExporter;
    }

    public ArrayList<AddedItem> getAdd_Item() {
        return add_Item;
    }

    public void setAdd_Item(ArrayList<AddedItem> add_Item) {
        this.add_Item = add_Item;
    }

    public double getDiscount() {
        return discount;
    }

    public void setDiscount(double discount) {
        this.discount = discount;
    }

    public boolean isNoExistence() {
        return noExistence;
    }

    public void setNoExistence(boolean noExistence) {
        this.noExistence = noExistence;
    }

    public double getPaied() {
        return paied;
    }

    public void setPaied(double paied) {
        this.paied = paied;
    }

    public int getBillNumber() {
        return billNumber;
    }

    public void setBillNumber(int billNumber) {
        this.billNumber = billNumber;
    }

    public int getDocNumber() {
        return docNumber;
    }

    public void setDocNumber(int docNumber) {
        this.docNumber = docNumber;
    }

    public double getBalanceAfterBill() {
         if(selectedExporter!=null){
            return bill_reminder + selectedExporter.getBalance();
         }else{
             return 0;
         }
    }

    public void setBalanceAfterBill(double balanceAfterBill) {
        this.balanceAfterBill = balanceAfterBill;
    }

    public double getBillTotal() {
        billTotal = 0;        
        try {
            for (Iterator<AddedItem> it = add_Item.iterator(); it.hasNext();) {
                AddedItem item = it.next();
                if (item.getBillItemStatus().equalsIgnoreCase("Regular") || item.getBillItemStatus().equalsIgnoreCase("") || item.getBillItemStatus() == null) {
                    billTotal += item.getTotoal_price();
                }
                if (item.getBillItemStatus().equalsIgnoreCase("ProductExecution")) {
                    billTotal -= item.getTotoal_price();
                }
            }
            billTotal = billTotal - discount;
            return billTotal;
        } catch (Exception e) {
            return billTotal;
        }
    }

    public void setBillTotal(double billTotal) {
        this.billTotal = billTotal;
    }

    public double getBill_reminder() {
        bill_reminder = paied-billTotal ;
        return bill_reminder;
    }

    public void setBill_reminder(double bill_reminder) {
        this.bill_reminder = bill_reminder;
    }

    //===========================================buttons method ======================================
    public String addAction() {

        int totalAdded = 0;
        for (Iterator<Quantity_Number> it = orderList.iterator(); it.hasNext();) {
            Quantity_Number qu = it.next();
            totalAdded += qu.getQuantity();


        }

        System.out.println(" total added = " + totalAdded + "TOTAL NUMBER IS = " + total_Number);
        if (!(totalAdded >= total_Number)) {
            Quantity_Number order = new Quantity_Number(quantity, number_quantity, getTotalRow(), getTotalKg());
            orderList.add(order);
        }


        return null;
    }

    public List<String> autocomplete(String inputValue) {
        System.out.println(" input value--------------------------------------------------" + inputValue);
        List<Exporter> objList = getFacade().getExporterByNameOrID(inputValue);
        System.out.println(" size is " + objList.size());
        List<String> df = new ArrayList<String>();
        for (Iterator<Exporter> it = objList.iterator(); it.hasNext();) {
            Exporter emp = it.next();
            df.add(emp.getExporterName());
        }
        return df;
    }

    public String add_item() {
        System.out.println(" get unit price in method add_item " + getUnite_price() + "tottttttttttttttttttttt" + totalKg + "--------" + totalRow);
        System.out.println(" infoooo selected country  " + selectedCountry + "selected sub item" + selectedsubItem + "unit   price " + unite_price + "to number quantity" + getNumber_quantity());
        System.out.println("factory :;::::::::" + factory);
        try {
            Factory tempFactory = ejbFacade.getFactoryById(Integer.parseInt(factory));
            Country tempCountry = ejbFacade.getCountryById(Integer.parseInt(selectedCountry));
            AddedItem newItem = new AddedItem(tempCountry.getCountryName(), tempFactory.getFactoryName(), selectedsubItem, unite_price, total_price,total_Number, totalKg,  expDate, false,billItemStatus);
            add_Item.add(newItem);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public BillFacade getBillFacad() {
        return billFacad;
    }

    public String commitValues() {
        clearSession();
        loger = new Loger(getLogFacade());
        List<Bill> bills=  billFacad.billCheckexporter(getBillNumber(), getDocNumber(),getBillDate());
        if(bills ==null || bills.size()==0){

        // update exporter information 
      // System.out.println(" balance after bill added " + getBalanceAfterBill());



        // Create Bill 
        Bill newBill = new Bill();
        newBill.setBillCach(paied);
        newBill.setBillNumber(getBillNumber());    // should not be constant 
        newBill.setBillReminder(bill_reminder);
        newBill.setBillTotal(billTotal);
        newBill.setExporterID(selectedExporter);
        newBill.setDisCount(discount);
        newBill.setCreateDate(billDate);
        newBill.setDocNum(getDocNumber());                    /// unknown
        newBill.setCustomerID(new Customer(-1));
        newBill.setTempFlag(1);
        if (noExistence) {
            newBill.setNonexistentFlag(1);                  /////     
        } else {
            newBill.setNonexistentFlag(0);                  ///// 
        }

        billFacad.create(newBill);
        /// Loop Over Bill Add in last table 
        for (Iterator<AddedItem> it = add_Item.iterator(); it.hasNext();) {
            AddedItem billitem = it.next();

            Factory tempfactory = ejbFacade.getFactoryByName(billitem.getFactory());

            Country tempcountry = ejbFacade.getCountryByName(billitem.getCountry());
            Item item = getFacade().getItemByFactoryAndCountry(billitem.getItem(), tempfactory);
            /// updating Item amount 
//            item.setPk_Count(item.getPk_Count() + billitem.getItem_quantity());
//            item.setQuantity(item.getQuantity() + billitem.getItem_count());
//
//
//            itemFacad.edit(item);

            BillItem newBillItem = new BillItem();
            newBillItem.setBillID(newBill);
            newBillItem.setFactoryID(tempfactory);

            newBillItem.setItemAmount(billitem.getItem_quantity());
            newBillItem.setItemPrice(billitem.getUnit_price());
            newBillItem.setPackageCount( billitem.getItem_count());
            newBillItem.setTotalPrice(billitem.getTotoal_price());
            newBillItem.setItemID(item);
            newBillItem.setExportBill(1);
            newBillItem.setItemEXPDate(billitem.getExpDate());
            newBillItem.setBillItemStatus(billitem.getBillItemStatus());
            billItemFacad.create(newBillItem);
        }

        // selectedExporter.setBalance(getBalanceAfterBill());
        //exporterFacad.edit(selectedExporter);
        String s = "تم اضافة فاتوره رقم ";
        String sd = "دفتر رقم ";
        String ss = " جديده للمورد :";
        String t = "باجمالي : ";
        String d = "في تاريخ";
        loger.LogerString(s + newBill.getBillNumber() + sd + newBill.getDocNum() + ss + selectedExporter.getExporterName() + "  " + d + " " + newBill.getCreateDate() + " " + t + newBill.getBillTotal(), 0);
        clear();
        billNumber++;
//        docNumber = (billNumber % 50) + 1;
        }else{
            JsfUtil.addErrorMessage( ResourceBundle.getBundle("/Bundle").getString("Billadderror"));
        }
        return null;
    }

    public String confirmValues() {
        loger = new Loger(getLogFacade());
       
        // Create Bill 
        Bill newBill = getBill();
        newBill.setBillCach(paied);
        newBill.setBillNumber(billNumber);
        newBill.setBillReminder(bill_reminder);
        newBill.setBillTotal(billTotal);
        newBill.setCreateDate(billDate);
        newBill.setExporterID(selectedExporter);
        newBill.setDisCount(discount);
        newBill.setDocNum(docNumber);
        newBill.setCustomerID(new Customer(-1));
        newBill.setTempFlag(0);
        if (noExistence) {
            newBill.setNonexistentFlag(1);    
        } else {
            newBill.setNonexistentFlag(0);  
        }
        billFacad.edit(newBill);
        
        //remove from bill_item
        for (BillItem billItem : billItemFacad.getBillItems(bill.getIdBill())) {
            billItemFacad.remove(billItem);
        }

        // Loop Over Bill Add in +last table 
        for (Iterator<AddedItem> it = add_Item.iterator(); it.hasNext();) {
            AddedItem billitem = it.next();
            
            Factory tempfactory = ejbFacade.getFactoryByName(billitem.getFactory());
            Item item = getFacade().getItemByFactoryAndCountry(billitem.getItem(), tempfactory);
            
             if (billitem.getBillItemStatus().equalsIgnoreCase("ProductExecution")) {
                // updating Item number of packages  
                item.setPk_Count(item.getPk_Count());
                // updating item quantity
                item.setQuantity(item.getQuantity());
                //adjusting customer balance
            }
            if (billitem.getBillItemStatus().equalsIgnoreCase("Regular") || billitem.getBillItemStatus().equalsIgnoreCase("") || billitem.getBillItemStatus() == null) {
                // updating Item number of packages 
                item.setPk_Count(item.getPk_Count() + billitem.getItem_count());
                // updating item quantity
                item.setQuantity(item.getQuantity() + billitem.getItem_quantity());
            }
            itemFacad.edit(item);

            BillItem newBillItem = new BillItem();
            newBillItem.setBillID(newBill);
            newBillItem.setFactoryID(tempfactory);
            newBillItem.setItemAmount(billitem.getItem_quantity());
            newBillItem.setItemPrice(billitem.getUnit_price());
            newBillItem.setPackageCount(billitem.getItem_count());
            newBillItem.setTotalPrice(billitem.getTotoal_price());
            newBillItem.setItemID(item);
            newBillItem.setExportBill(1);
            newBillItem.setItemEXPDate(billitem.getExpDate());
            newBillItem.setBillItemStatus(billitem.getBillItemStatus());
            billItemFacad.create(newBillItem);
        }
        
        //update exporter information 
        selectedExporter.setBalance(getBalanceAfterBill());
        exporterFacad.edit(selectedExporter);
        
        //logging
        String s = "تم تاكيد فاتوره رقم ";
        String sd = "دفتر رقم ";
        String ss = "  للمورد :";
        String t = "باجمالي : ";
        String d = "في تاريخ";
        loger.LogerString(s + newBill.getBillNumber() + sd + newBill.getDocNum() + ss + selectedExporter.getExporterName() + "  " + d + " " + getCDate() + " " + t + bill.getBillTotal(), 0);
        
        //saving action details into treasury
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        Treausry treausry = new Treausry();
        treausry.setActionDate(billDate);
        treausry.setCustomerId(null);
        treausry.setEmployeeId(new Employee(Integer.parseInt(session.getValue("empid").toString())));
        treausry.setExporterId(selectedExporter);
        treausry.setGeneralDescription(s + newBill.getBillNumber() + sd + newBill.getDocNum() + ss + selectedExporter.getExporterName() );
        treausry.setMoneyAmount(-1 * bill.getBillCach());
        treausry.setBillId(newBill);
        treausryFacade.create(treausry);
        
        itemController.prepare();
        clear();
        clearSession();
        return "confirmBills";
    }

    public String testAjax() {
        System.out.println(" excuting ajax ");
        return "";
    }

    public String deleteAction(AddedItem order) {

        add_Item.remove(order);
        return null;
    }

    public ExporterFacade getExporterFacad() {
        return exporterFacad;
    }

    /**
     * @return the CDate
     */
    public String getCDate() {
SimpleDateFormat dateFormat=new SimpleDateFormat("dd/MM/yyyy");
        System.out.println("billDate:"+billDate);
      CDate=  dateFormat.format(billDate);
        return CDate;
    }

    /**
     * @param CDate the CDate to set
     */
    public void setCDate(String CDate) {
        this.CDate = CDate;
    }

    public String calculateTotalOnBlur() {
        total_price = unite_price * number_quantity;
        System.out.println(" total prise is " + total_price);
        return null;
    }

    public Date getExpDate() {
        return expDate;
    }

    public void setExpDate(Date expDate) {
        this.expDate = expDate;
    }

    public String editAction(AddedItem order) {

        order.setEditable(true);
        return null;
    }

    public String saveAction(AddedItem order2) {
        System.out.println("list:" + order2.getItem_quantity());
        //get all existing value but set "editable" to false 
        order2.setTotoal_price(order2.getUnit_price() * order2.getItem_quantity());
//        for (AddedItem order : add_Item) {
//
        order2.setEditable(false);
//        }

        //return to current page
        return null;

    }

    public Bill getBill() {
        return bill;
    }

    public void setBill(Bill bill) {
        this.bill = bill;
    }

    public LogFacade getLogFacade() {
        return logFacade;
    }

    public void setLogFacade(LogFacade logFacade) {
        this.logFacade = logFacade;
    }

    public TreausryFacade getTreausryFacade() {
        return treausryFacade;
    }

    public void setTreausryFacade(TreausryFacade treausryFacade) {
        this.treausryFacade = treausryFacade;
    }

    public void clear() {
        selectedExporter = null;
        add_Item.clear();
        balanceAfterBill = 0.0;
        // billNumber++;
        billTotal = 0.0;
        bill_reminder = 0.0;
        exporterName = "";
        discount = 0.0;
        noExistence = false;
        unite_price = 0.0;
        totalKg = 0.0;
        total_Number = 0.0;
        number_quantity = 0;
        balanceAfterBill = 0.0;
        paied = 0.0;
        selectedCountry = "";
        selectedsubItem = "";
    }

    public Date getBillDate() {
        return billDate;
    }

    public void setBillDate(Date billDate) {
        this.billDate = billDate;
    }

    public ItemController getItemController() {
        return itemController;
    }

    public void setItemController(ItemController itemController) {
        this.itemController = itemController;
    }

    public CountryFacade getCountryFacade() {
        return countryFacade;
    }

    public void setCountryFacade(CountryFacade countryFacade) {
        this.countryFacade = countryFacade;
    }
    public void  clearSession(){
    Map m=  FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
    m.remove("exporterController");   
    
m.remove("employeeController"); 
m.remove("customerController"); 
m.remove("countryController"); 
m.remove("billInformationController"); 
m.remove("inventoryStoreController"); 
m.remove("moneyController"); 
m.remove("billConfirmController"); 
m.remove("billExporterInformationController"); 
m.remove("logController"); 
m.remove("itemController"); 

    }

}
